import { NextRequest } from 'next/server';

export const dynamic = 'force-dynamic';

export async function GET(request: NextRequest) {
  const searchParams = request.nextUrl.searchParams;
  const path = searchParams.get('path');
  const interviewId = searchParams.get('interviewId');
  const query = searchParams.get('query');
  const imagePath = searchParams.get('imagePath');

  if (!path) {
    return new Response('Path is required', { status: 400 });
  }

  try {
    // 构建请求URL - 使用正确的API路径
    const apiUrl = `http://localhost:8101${path}`;
    
    // 创建请求选项
    const options: RequestInit = {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'text/event-stream',
      },
      credentials: 'include',
    };

    // 构建请求体
    if (path.includes('chatByMuitiStream')) {
      if (!imagePath) {
        return new Response('图片路径不能为空', { status: 400 });
      }
      
      console.log('使用chatByMuitiStream API，图片路径:', imagePath);
      
      options.body = JSON.stringify({
        interviewId: Number(interviewId),
        query,
        imagePath,
      });
    } else if (path.includes('chatStream')) {
      options.body = JSON.stringify({
        interviewId: Number(interviewId),
        query,
      });
    }

    console.log(`Sending request to ${apiUrl} with options:`, options);

    // 发送请求到后端API
    const response = await fetch(apiUrl, options);

    if (!response.ok) {
      console.error(`Backend API error: ${response.status}`);
      const errorText = await response.text();
      console.error(`Backend API error details:`, errorText);
      return new Response(`Backend API error: ${response.status} - ${errorText}`, { status: response.status });
    }

    // 检查响应类型
    const contentType = response.headers.get('content-type');
    console.log('Backend response content-type:', contentType);

    // 创建一个TransformStream来处理响应
    const { readable, writable } = new TransformStream();
    const writer = writable.getWriter();
    const encoder = new TextEncoder();

    // 处理后端响应流
    const reader = response.body?.getReader();
    if (!reader) {
      console.error('Failed to get reader from response body');
      return new Response('Failed to get response reader', { status: 500 });
    }

    // 开始读取流
    (async () => {
      try {
        const decoder = new TextDecoder();
        
        while (true) {
          const { done, value } = await reader.read();
          
          if (done) {
            console.log("Stream reading complete, sending end event");
            
            // 发送结束事件
            await writer.write(encoder.encode('event: end\ndata: [DONE]\n\n'));
            await writer.close();
            break;
          }
          
          // 解码接收到的数据
          const chunk = decoder.decode(value, { stream: true });
          console.log("Received chunk from backend:", chunk);
          
          // 处理SSE格式数据
          const lines = chunk.split('\n');
          for (const line of lines) {
            if (line.startsWith('data:')) {
              const content = line.slice(5).trim();
              if (content) {
                console.log("Sending to client:", content);
                // 逐个字符发送以实现打字机效果
                for (const char of content) {
                  await writer.write(encoder.encode(`data: ${char}\n\n`));
                  // 添加小延迟以获得更好的打字机效果
                  await new Promise(resolve => setTimeout(resolve, 10));
                }
              }
            } else if (line.trim() && !line.includes('event:')) {
              // 直接发送非空且不是event的行
              console.log("Sending raw line to client:", line);
              await writer.write(encoder.encode(`data: ${line}\n\n`));
            }
          }
        }
      } catch (error) {
        console.error('Error reading from response stream:', error);
        await writer.write(encoder.encode(`data: Error: ${error instanceof Error ? error.message : String(error)}\n\n`));
        await writer.write(encoder.encode('event: end\ndata: [DONE]\n\n'));
        await writer.close();
      }
    })();

    // 返回SSE响应
    return new Response(readable, {
      headers: {
        'Content-Type': 'text/event-stream',
        'Cache-Control': 'no-cache',
        'Connection': 'keep-alive',
      },
    });
  } catch (error) {
    console.error('SSE API error:', error);
    return new Response(`Server error: ${error instanceof Error ? error.message : String(error)}`, { status: 500 });
  }
} 